package cn.edu.ctbu.api01.service;
import cn.edu.ctbu.api01.domain.Student;
import cn.edu.ctbu.api01.helper.PageUtils;
import cn.edu.ctbu.api01.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Pageable;
import java.util.Collections;
import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;
    public Page<Student> findAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    };

    public List<Student> findAll() {
        return studentRepository.findAll();
    }
    //按id进行查询
    public Student findById(Integer id) {
        Student student=studentRepository.findById(id).orElse(null);
        return student;
    }
    //按名字进行查询
    public List<Student> findByName(String name) {
        return studentRepository.findByNameLike(name);
    }
    //增加
    public Student insert(Student student) {
        studentRepository.save(student);
        return student;
    }
    //修改
    public Student update(Student student) {
        studentRepository.save(student);
        return student;
    }
    //删除
    public void deletebyid(Integer id) {
        Student student=new Student();
        student.setId(id);
        studentRepository.deleteById(id);
    }
    public void delete(Student student) {
        studentRepository.delete(student);
    }
    public List<Student> searchStudentsByTerm(String term, String type) {
        if ("name".equals(type)) {
            return studentRepository.findByNameLike("%" + term + "%");
        } else if ("id".equals(type)) {
            Integer id = Integer.parseInt(term);
            return Collections.singletonList(studentRepository.findById(id).orElse(null));
        } else {
            // 如果不是有效的查询类型，则返回空列表
            return Collections.emptyList();
        }
    }
//    public List<Student> findStudentsWithMaxNo() {
//        return studentRepository.findStudentsWithMaxNo();
//    }

    public Boolean validUserNameAndPassword(String userName,String password) throws Exception{
        List<Student> students=studentRepository.findByNameAndPassword(userName,password);
        if(students.size()>0){
            return true;    //找到用户
        }else {
            throw new Exception("出错了，无效的用户名和密码！");
        }
    }
}